/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import opiam.admin.applis.demo.beans.Person;
import opiam.admin.faare.persistence.LdapObjectFilter;
import opiam.admin.faare.persistence.javabeans.JBTop;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.services.StandardService;
import opiam.admin.faare.service.services.views.ViewGenerator;
import opiam.admin.faare.service.services.views.orgchart.OrgChartPanel;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;


/**
 * This class allows to generate a graphic orgchart.
 */
public class GraphicOrgChartAction extends SecureAction
{
    /** Instance of the log4j logger.
     * Used to generate the execution traces. */
    private static Logger _logger =
        Logger.getLogger(GraphicOrgChartAction.class.getName());

    /**
     * This method is called to execute the action.
     *
     * @param mapping              Struts mapping data.
     * @param actionForm           FormBean associated with the action.
     * @param request              HTTP request.
     * @param httpServletResponse  HTTP response.
     *
     * @return An ActionForward.
     *
     * @throws IOException  An I/O exception if failed or interrupted I/O operations occurs.
     * @throws ServletException  A ServletException if the servlet has a problem.
     */
    @Override
	public ActionForward secureExecute(ActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse httpServletResponse
                                      ) throws IOException, ServletException
    {
        SessionContext sessionContext = null;
        UserContext userContext = null;
        ActionMessages msgErrors = new ActionMessages();

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();

            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);

            // Gets the user context.
            userContext = sessionContext.getUserContext();

            String type = request.getParameter("type");
            String viewName = request.getParameter("viewName");
            String levelStr = request.getParameter("levelStr");
            int level = Integer.parseInt(levelStr);
            String direction = request.getParameter("direction");
            String mode = request.getParameter("mode");
            String dn = request.getParameter("dn");

            JBTop loadedObj = StandardService.load(dn, userContext);

            // Converts the entry in Person entry.
            Person person = (Person) loadedObj;
            userContext.getParameters().put(LdapObjectFilter.VAR_CURRENT_ITEM, person);
            _logger.debug("current_item = " + person.getDn());

            List lresult =
                ViewGenerator.generateOrgChartAsJpgOrPng(person, viewName,
                                                         level, direction,
                                                         mode, userContext, type
                                                        );

            session.setAttribute("IMG", lresult.get(0));
            
            Iterator iter = ((List) lresult.get(1)).iterator();
            StringBuffer map = new StringBuffer("<map name='orgchart'>");

            while (iter.hasNext())
            {
                Hashtable info = (Hashtable) iter.next();
                int x1 = ((Integer) info.get(OrgChartPanel.XCOORD)).intValue();
                int y1 = ((Integer) info.get(OrgChartPanel.YCOORD)).intValue();
                int w = ((Integer) info.get(OrgChartPanel.WIDTH)).intValue();
                int h = ((Integer) info.get(OrgChartPanel.HEIGHT)).intValue();
                int x2 = x1 + w;
                int y2 = y1 + h;
                map.append("<area shape='rect' coords='" + x1 + "," + y1 + "," +
                           x2 + "," + y2 + "'href='" +
                           "showPerson.do?dn=" + info.get(OrgChartPanel.DN) +
                           "'/>"+""
                          );
            }

            map.append("</map>");
            //String testMap = "<map name='orgchart'><area shape='rect' coords='0,3325,172,3375'href='showPerson.do?dn=uid=kvaughan,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='232,250,404,300'href='showPerson.do?dn=uid=abergin,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='232,1150,404,1200'href='showPerson.do?dn=uid=scarter,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='232,2080,404,2130'href='showPerson.do?dn=uid=achassin,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='232,2920,404,2970'href='showPerson.do?dn=uid=tmorris,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='232,3880,404,3930'href='showPerson.do?dn=uid=trigden,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='232,4900,404,4950'href='showPerson.do?dn=uid=cschmith,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='232,4960,404,5010'href='showPerson.do?dn=uid=ythestay,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='232,5680,404,5730'href='showPerson.do?dn=uid=jwalker,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='232,6400,404,6450'href='showPerson.do?dn=uid=kwinters,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,10,636,60'href='showPerson.do?dn=uid=pcruse,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,70,636,120'href='showPerson.do?dn=uid=jlange,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,130,636,180'href='showPerson.do?dn=uid=brentz,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,190,636,240'href='showPerson.do?dn=uid=jreuter,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,250,636,300'href='showPerson.do?dn=uid=bschneid,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,310,636,360'href='showPerson.do?dn=uid=lstockto,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,370,636,420'href='showPerson.do?dn=uid=lulrich,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,430,636,480'href='showPerson.do?dn=uid=dward,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,490,636,540'href='showPerson.do?dn=uid=awhite,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,550,636,600'href='showPerson.do?dn=uid=falbers,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,610,636,660'href='showPerson.do?dn=uid=lcampbel,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,670,636,720'href='showPerson.do?dn=uid=gfarmer,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,730,636,780'href='showPerson.do?dn=uid=bhal2,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,790,636,840'href='showPerson.do?dn=uid=ahel,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,850,636,900'href='showPerson.do?dn=uid=ejohnson,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,910,636,960'href='showPerson.do?dn=uid=ekohler,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,970,636,1020'href='showPerson.do?dn=uid=jmcfarla,ou=people,dc=mycompany,dc=com'/><area shape='rect' coords='464,1030,636,1080'href='showPerson.do?dn=uid=dmiller,ou=people,dc=mycompany,dc=com'/></map>";
            session.setAttribute("orgmap", map.toString());
            _logger.debug("orgmap");
            _logger.debug(map.toString());

            // puts the parameters in the request to enable to create a pdf orgchart.
            request.setAttribute("viewName", viewName);
            request.setAttribute("levelStr", levelStr);
            request.setAttribute("direction", direction);
            request.setAttribute("mode", mode);
            request.setAttribute("dn", dn);

            return (mapping.findForward("success"));
        }
        catch (Exception se)
        {
            _logger.error(se.getMessage());
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                          new ActionMessage("error.service.unknown")
                         );
            saveErrors(request, msgErrors);

            return (mapping.findForward("service_error"));
        }
    }
}
